{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\nAnnotations\n===========\n\nAnnotating text with Matplotlib.\n   :depth: 3\n\n\nBasic annotation\n================\n\nThe uses of the basic :func:`~matplotlib.pyplot.text` will place text\nat an arbitrary position on the Axes.  A common use case of text is to\nannotate some feature of the plot, and the\n:func:`~matplotlib.Axes.annotate` method provides helper functionality\nto make annotations easy.  In an annotation, there are two points to\nconsider: the location being annotated represented by the argument\n``xy`` and the location of the text ``xytext``.  Both of these\narguments are ``(x,y)`` tuples.\n\n.. figure:: ../../gallery/pyplots/images/sphx_glr_annotation_basic_001.png\n   :target: ../../gallery/pyplots/annotation_basic.html\n   :align: center\n   :scale: 50\n\n   Annotation Basic\n\nIn this example, both the ``xy`` (arrow tip) and ``xytext`` locations\n(text location) are in data coordinates.  There are a variety of other\ncoordinate systems one can choose -- you can specify the coordinate\nsystem of ``xy`` and ``xytext`` with one of the following strings for\n``xycoords`` and ``textcoords`` (default is 'data')\n\n====================  ====================================================\nargument              coordinate system\n====================  ====================================================\n  'figure points'     points from the lower left corner of the figure\n  'figure pixels'     pixels from the lower left corner of the figure\n  'figure fraction'   0,0 is lower left of figure and 1,1 is upper right\n  'axes points'       points from lower left corner of axes\n  'axes pixels'       pixels from lower left corner of axes\n  'axes fraction'     0,0 is lower left of axes and 1,1 is upper right\n  'data'              use the axes data coordinate system\n====================  ====================================================\n\nFor example to place the text coordinates in fractional axes\ncoordinates, one could do::\n\n    ax.annotate('local max', xy=(3, 1),  xycoords='data',\n                xytext=(0.8, 0.95), textcoords='axes fraction',\n                arrowprops=dict(facecolor='black', shrink=0.05),\n                horizontalalignment='right', verticalalignment='top',\n                )\n\nFor physical coordinate systems (points or pixels) the origin is the\nbottom-left of the figure or axes.\n\nOptionally, you can enable drawing of an arrow from the text to the annotated\npoint by giving a dictionary of arrow properties in the optional keyword\nargument ``arrowprops``.\n\n\n==================== =====================================================\n``arrowprops`` key   description\n==================== =====================================================\nwidth                the width of the arrow in points\nfrac                 the fraction of the arrow length occupied by the head\nheadwidth            the width of the base of the arrow head in points\nshrink               move the tip and base some percent away from\n                     the annotated point and text\n\n\\*\\*kwargs           any key for :class:`matplotlib.patches.Polygon`,\n                     e.g., ``facecolor``\n==================== =====================================================\n\n\nIn the example below, the ``xy`` point is in native coordinates\n(``xycoords`` defaults to 'data').  For a polar axes, this is in\n(theta, radius) space.  The text in this example is placed in the\nfractional figure coordinate system. :class:`matplotlib.text.Text`\nkeyword args like ``horizontalalignment``, ``verticalalignment`` and\n``fontsize`` are passed from `~matplotlib.Axes.annotate` to the\n``Text`` instance.\n\n.. figure:: ../../gallery/pyplots/images/sphx_glr_annotation_polar_001.png\n   :target: ../../gallery/pyplots/annotation_polar.html\n   :align: center\n   :scale: 50\n\n   Annotation Polar\n\nFor more on all the wild and wonderful things you can do with\nannotations, including fancy arrows, see `plotting-guide-annotation`\nand :doc:`/gallery/text_labels_and_annotations/annotation_demo`.\n\n\nDo not proceed unless you have already read `annotations-tutorial`,\n:func:`~matplotlib.pyplot.text` and :func:`~matplotlib.pyplot.annotate`!\n\n\n\nAdvanced Annotation\n===================\n\n\nAnnotating with Text with Box\n-----------------------------\n\nLet's start with a simple example.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_text_arrow_001.png\n   :target: ../../gallery/userdemo/annotate_text_arrow.html\n   :align: center\n   :scale: 50\n\n   Annotate Text Arrow\n\n\nThe :func:`~matplotlib.pyplot.text` function in the pyplot module (or\ntext method of the Axes class) takes bbox keyword argument, and when\ngiven, a box around the text is drawn. ::\n\n    bbox_props = dict(boxstyle=\"rarrow,pad=0.3\", fc=\"cyan\", ec=\"b\", lw=2)\n    t = ax.text(0, 0, \"Direction\", ha=\"center\", va=\"center\", rotation=45,\n                size=15,\n                bbox=bbox_props)\n\n\nThe patch object associated with the text can be accessed by::\n\n    bb = t.get_bbox_patch()\n\nThe return value is an instance of FancyBboxPatch and the patch\nproperties like facecolor, edgewidth, etc. can be accessed and\nmodified as usual. To change the shape of the box, use the *set_boxstyle*\nmethod. ::\n\n  bb.set_boxstyle(\"rarrow\", pad=0.6)\n\nThe arguments are the name of the box style with its attributes as\nkeyword arguments. Currently, following box styles are implemented.\n\n  ==========   ==============   ==========================\n  Class        Name             Attrs\n  ==========   ==============   ==========================\n  Circle       ``circle``       pad=0.3\n  DArrow       ``darrow``       pad=0.3\n  LArrow       ``larrow``       pad=0.3\n  RArrow       ``rarrow``       pad=0.3\n  Round        ``round``        pad=0.3,rounding_size=None\n  Round4       ``round4``       pad=0.3,rounding_size=None\n  Roundtooth   ``roundtooth``   pad=0.3,tooth_size=None\n  Sawtooth     ``sawtooth``     pad=0.3,tooth_size=None\n  Square       ``square``       pad=0.3\n  ==========   ==============   ==========================\n\n.. figure:: ../../gallery/shapes_and_collections/images/sphx_glr_fancybox_demo_001.png\n   :target: ../../gallery/shapes_and_collections/fancybox_demo.html\n   :align: center\n   :scale: 50\n\n   Fancybox Demo\n\n\nNote that the attribute arguments can be specified within the style\nname with separating comma (this form can be used as \"boxstyle\" value\nof bbox argument when initializing the text instance) ::\n\n   bb.set_boxstyle(\"rarrow,pad=0.6\")\n\n\n\n\nAnnotating with Arrow\n---------------------\n\nThe :func:`~matplotlib.pyplot.annotate` function in the pyplot module\n(or annotate method of the Axes class) is used to draw an arrow\nconnecting two points on the plot. ::\n\n    ax.annotate(\"Annotation\",\n                xy=(x1, y1), xycoords='data',\n                xytext=(x2, y2), textcoords='offset points',\n                )\n\nThis annotates a point at ``xy`` in the given coordinate (``xycoords``)\nwith the text at ``xytext`` given in ``textcoords``. Often, the\nannotated point is specified in the *data* coordinate and the annotating\ntext in *offset points*.\nSee :func:`~matplotlib.pyplot.annotate` for available coordinate systems.\n\nAn arrow connecting two points (xy & xytext) can be optionally drawn by\nspecifying the ``arrowprops`` argument. To draw only an arrow, use\nempty string as the first argument. ::\n\n    ax.annotate(\"\",\n                xy=(0.2, 0.2), xycoords='data',\n                xytext=(0.8, 0.8), textcoords='data',\n                arrowprops=dict(arrowstyle=\"->\",\n                                connectionstyle=\"arc3\"),\n                )\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple01_001.png\n   :target: ../../gallery/userdemo/annotate_simple01.html\n   :align: center\n   :scale: 50\n\n   Annotate Simple01\n\nThe arrow drawing takes a few steps.\n\n1. a connecting path between two points are created. This is\n   controlled by ``connectionstyle`` key value.\n\n2. If patch object is given (*patchA* & *patchB*), the path is clipped to\n   avoid the patch.\n\n3. The path is further shrunk by given amount of pixels (*shrinkA*\n   & *shrinkB*)\n\n4. The path is transmuted to arrow patch, which is controlled by the\n   ``arrowstyle`` key value.\n\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_explain_001.png\n   :target: ../../gallery/userdemo/annotate_explain.html\n   :align: center\n   :scale: 50\n\n   Annotate Explain\n\n\nThe creation of the connecting path between two points is controlled by\n``connectionstyle`` key and the following styles are available.\n\n   ==========   =============================================\n   Name         Attrs\n   ==========   =============================================\n   ``angle``    angleA=90,angleB=0,rad=0.0\n   ``angle3``   angleA=90,angleB=0\n   ``arc``      angleA=0,angleB=0,armA=None,armB=None,rad=0.0\n   ``arc3``     rad=0.0\n   ``bar``      armA=0.0,armB=0.0,fraction=0.3,angle=None\n   ==========   =============================================\n\nNote that \"3\" in ``angle3`` and ``arc3`` is meant to indicate that the\nresulting path is a quadratic spline segment (three control\npoints). As will be discussed below, some arrow style options can only\nbe used when the connecting path is a quadratic spline.\n\nThe behavior of each connection style is (limitedly) demonstrated in the\nexample below. (Warning : The behavior of the ``bar`` style is currently not\nwell defined, it may be changed in the future).\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_connectionstyle_demo_001.png\n   :target: ../../gallery/userdemo/connectionstyle_demo.html\n   :align: center\n   :scale: 50\n\n   Connectionstyle Demo\n\n\nThe connecting path (after clipping and shrinking) is then mutated to\nan arrow patch, according to the given ``arrowstyle``.\n\n    ==========   =============================================\n    Name         Attrs\n    ==========   =============================================\n    ``-``        None\n    ``->``       head_length=0.4,head_width=0.2\n    ``-[``       widthB=1.0,lengthB=0.2,angleB=None\n    ``|-|``      widthA=1.0,widthB=1.0\n    ``-|>``      head_length=0.4,head_width=0.2\n    ``<-``       head_length=0.4,head_width=0.2\n    ``<->``      head_length=0.4,head_width=0.2\n    ``<|-``      head_length=0.4,head_width=0.2\n    ``<|-|>``    head_length=0.4,head_width=0.2\n    ``fancy``    head_length=0.4,head_width=0.4,tail_width=0.4\n    ``simple``   head_length=0.5,head_width=0.5,tail_width=0.2\n    ``wedge``    tail_width=0.3,shrink_factor=0.5\n    ==========   =============================================\n\n.. figure:: ../../gallery/text_labels_and_annotations/images/sphx_glr_fancyarrow_demo_001.png\n   :target: ../../gallery/text_labels_and_annotations/fancyarrow_demo.html\n   :align: center\n   :scale: 50\n\n   Fancyarrow Demo\n\nSome arrowstyles only work with connection styles that generate a\nquadratic-spline segment. They are ``fancy``, ``simple``, and ``wedge``.\nFor these arrow styles, you must use the \"angle3\" or \"arc3\" connection\nstyle.\n\nIf the annotation string is given, the patchA is set to the bbox patch\nof the text by default.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple02_001.png\n   :target: ../../gallery/userdemo/annotate_simple02.html\n   :align: center\n   :scale: 50\n\n   Annotate Simple02\n\nAs in the text command, a box around the text can be drawn using\nthe ``bbox`` argument.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple03_001.png\n   :target: ../../gallery/userdemo/annotate_simple03.html\n   :align: center\n   :scale: 50\n\n   Annotate Simple03\n\nBy default, the starting point is set to the center of the text\nextent.  This can be adjusted with ``relpos`` key value. The values\nare normalized to the extent of the text. For example, (0,0) means\nlower-left corner and (1,1) means top-right.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple04_001.png\n   :target: ../../gallery/userdemo/annotate_simple04.html\n   :align: center\n   :scale: 50\n\n   Annotate Simple04\n\n\nPlacing Artist at the anchored location of the Axes\n---------------------------------------------------\n\nThere are classes of artists that can be placed at an anchored location\nin the Axes. A common example is the legend.  This type of artist can\nbe created by using the OffsetBox class. A few predefined classes are\navailable in ``mpl_toolkits.axes_grid1.anchored_artists`` others in\n``matplotlib.offsetbox`` ::\n\n    from matplotlib.offsetbox import AnchoredText\n    at = AnchoredText(\"Figure 1a\",\n                      prop=dict(size=15), frameon=True,\n                      loc='upper left',\n                      )\n    at.patch.set_boxstyle(\"round,pad=0.,rounding_size=0.2\")\n    ax.add_artist(at)\n\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_anchored_box01_001.png\n   :target: ../../gallery/userdemo/anchored_box01.html\n   :align: center\n   :scale: 50\n\n   Anchored Box01\n\n\nThe *loc* keyword has same meaning as in the legend command.\n\nA simple application is when the size of the artist (or collection of\nartists) is known in pixel size during the time of creation. For\nexample, If you want to draw a circle with fixed size of 20 pixel x 20\npixel (radius = 10 pixel), you can utilize\n``AnchoredDrawingArea``. The instance is created with a size of the\ndrawing area (in pixels), and arbitrary artists can added to the\ndrawing area. Note that the extents of the artists that are added to\nthe drawing area are not related to the placement of the drawing\narea itself. Only the initial size matters. ::\n\n    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea\n\n    ada = AnchoredDrawingArea(20, 20, 0, 0,\n                              loc='upper right', pad=0., frameon=False)\n    p1 = Circle((10, 10), 10)\n    ada.drawing_area.add_artist(p1)\n    p2 = Circle((30, 10), 5, fc=\"r\")\n    ada.drawing_area.add_artist(p2)\n\nThe artists that are added to the drawing area should not have a\ntransform set (it will be overridden) and the dimensions of those\nartists are interpreted as a pixel coordinate, i.e., the radius of the\ncircles in above example are 10 pixels and 5 pixels, respectively.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_anchored_box02_001.png\n   :target: ../../gallery/userdemo/anchored_box02.html\n   :align: center\n   :scale: 50\n\n   Anchored Box02\n\nSometimes, you want your artists to scale with the data coordinate (or\ncoordinates other than canvas pixels). You can use\n``AnchoredAuxTransformBox`` class. This is similar to\n``AnchoredDrawingArea`` except that the extent of the artist is\ndetermined during the drawing time respecting the specified transform. ::\n\n  from mpl_toolkits.axes_grid1.anchored_artists import AnchoredAuxTransformBox\n\n  box = AnchoredAuxTransformBox(ax.transData, loc='upper left')\n  el = Ellipse((0,0), width=0.1, height=0.4, angle=30)  # in data coordinates!\n  box.drawing_area.add_artist(el)\n\nThe ellipse in the above example will have width and height\ncorresponding to 0.1 and 0.4 in data coordinates and will be\nautomatically scaled when the view limits of the axes change.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_anchored_box03_001.png\n   :target: ../../gallery/userdemo/anchored_box03.html\n   :align: center\n   :scale: 50\n\n   Anchored Box03\n\nAs in the legend, the bbox_to_anchor argument can be set.  Using the\nHPacker and VPacker, you can have an arrangement(?) of artist as in the\nlegend (as a matter of fact, this is how the legend is created).\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_anchored_box04_001.png\n   :target: ../../gallery/userdemo/anchored_box04.html\n   :align: center\n   :scale: 50\n\n   Anchored Box04\n\nNote that unlike the legend, the ``bbox_transform`` is set\nto IdentityTransform by default.\n\nUsing Complex Coordinates with Annotations\n------------------------------------------\n\nThe Annotation in matplotlib supports several types of coordinates as\ndescribed in `annotations-tutorial`. For an advanced user who wants\nmore control, it supports a few other options.\n\n 1. :class:`~matplotlib.transforms.Transform` instance. For example, ::\n\n      ax.annotate(\"Test\", xy=(0.5, 0.5), xycoords=ax.transAxes)\n\n    is identical to ::\n\n      ax.annotate(\"Test\", xy=(0.5, 0.5), xycoords=\"axes fraction\")\n\n    With this, you can annotate a point in other axes. ::\n\n      ax1, ax2 = subplot(121), subplot(122)\n      ax2.annotate(\"Test\", xy=(0.5, 0.5), xycoords=ax1.transData,\n                   xytext=(0.5, 0.5), textcoords=ax2.transData,\n                   arrowprops=dict(arrowstyle=\"->\"))\n\n 2. :class:`~matplotlib.artist.Artist` instance. The xy value (or\n    xytext) is interpreted as a fractional coordinate of the bbox\n    (return value of *get_window_extent*) of the artist. ::\n\n      an1 = ax.annotate(\"Test 1\", xy=(0.5, 0.5), xycoords=\"data\",\n                        va=\"center\", ha=\"center\",\n                        bbox=dict(boxstyle=\"round\", fc=\"w\"))\n      an2 = ax.annotate(\"Test 2\", xy=(1, 0.5), xycoords=an1, # (1,0.5) of the an1's bbox\n                        xytext=(30,0), textcoords=\"offset points\",\n                        va=\"center\", ha=\"left\",\n                        bbox=dict(boxstyle=\"round\", fc=\"w\"),\n                        arrowprops=dict(arrowstyle=\"->\"))\n\n    .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple_coord01_001.png\n       :target: ../../gallery/userdemo/annotate_simple_coord01.html\n       :align: center\n       :scale: 50\n\n       Annotation with Simple Coordinates\n\n    Note that it is your responsibility that the extent of the\n    coordinate artist (*an1* in above example) is determined before *an2*\n    gets drawn. In most cases, it means that *an2* needs to be drawn\n    later than *an1*.\n\n\n 3. A callable object that returns an instance of either\n    :class:`~matplotlib.transforms.BboxBase` or\n    :class:`~matplotlib.transforms.Transform`. If a transform is\n    returned, it is the same as 1 and if a bbox is returned, it is the same\n    as 2.  The callable object should take a single argument of the\n    renderer instance. For example, the following two commands give\n    identical results ::\n\n      an2 = ax.annotate(\"Test 2\", xy=(1, 0.5), xycoords=an1,\n                        xytext=(30,0), textcoords=\"offset points\")\n      an2 = ax.annotate(\"Test 2\", xy=(1, 0.5), xycoords=an1.get_window_extent,\n                        xytext=(30,0), textcoords=\"offset points\")\n\n\n 4. A tuple of two coordinate specifications. The first item is for the\n    x-coordinate and the second is for the y-coordinate. For example, ::\n\n      annotate(\"Test\", xy=(0.5, 1), xycoords=(\"data\", \"axes fraction\"))\n\n    0.5 is in data coordinates, and 1 is in normalized axes coordinates.\n    You may use an artist or transform as with a tuple. For example,\n\n    .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple_coord02_001.png\n       :target: ../../gallery/userdemo/annotate_simple_coord02.html\n       :align: center\n       :scale: 50\n\n       Annotation with Simple Coordinates 2\n\n 5. Sometimes, you want your annotation with some \"offset points\", not from the\n    annotated point but from some other point.\n    :class:`~matplotlib.text.OffsetFrom` is a helper class for such cases.\n\n    .. figure:: ../../gallery/userdemo/images/sphx_glr_annotate_simple_coord03_001.png\n       :target: ../../gallery/userdemo/annotate_simple_coord03.html\n       :align: center\n       :scale: 50\n\n       Annotation with Simple Coordinates 3\n\n    You may take a look at this example\n    :doc:`/gallery/text_labels_and_annotations/annotation_demo`.\n\nUsing ConnectionPatch\n---------------------\n\nThe ConnectionPatch is like an annotation without text. While the annotate\nfunction is recommended in most situations, the ConnectionPatch is useful when\nyou want to connect points in different axes. ::\n\n  from matplotlib.patches import ConnectionPatch\n  xy = (0.2, 0.2)\n  con = ConnectionPatch(xyA=xy, xyB=xy, coordsA=\"data\", coordsB=\"data\",\n                        axesA=ax1, axesB=ax2)\n  ax2.add_artist(con)\n\nThe above code connects point xy in the data coordinates of ``ax1`` to\npoint xy in the data coordinates of ``ax2``. Here is a simple example.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_connect_simple01_001.png\n   :target: ../../gallery/userdemo/connect_simple01.html\n   :align: center\n   :scale: 50\n\n   Connect Simple01\n\n\nWhile the ConnectionPatch instance can be added to any axes, you may want to add\nit to the axes that is latest in drawing order to prevent overlap by other\naxes.\n\n\nAdvanced Topics\n~~~~~~~~~~~~~~~\n\nZoom effect between Axes\n------------------------\n\n``mpl_toolkits.axes_grid1.inset_locator`` defines some patch classes useful\nfor interconnecting two axes. Understanding the code requires some\nknowledge of how mpl's transform works. But, utilizing it will be\nstraight forward.\n\n\n.. figure:: ../../gallery/subplots_axes_and_figures/images/sphx_glr_axes_zoom_effect_001.png\n   :target: ../../gallery/subplots_axes_and_figures/axes_zoom_effect.html\n   :align: center\n   :scale: 50\n\n   Axes Zoom Effect\n\n\nDefine Custom BoxStyle\n----------------------\n\nYou can use a custom box style. The value for the ``boxstyle`` can be a\ncallable object in the following forms.::\n\n        def __call__(self, x0, y0, width, height, mutation_size,\n                     aspect_ratio=1.):\n            '''\n            Given the location and size of the box, return the path of\n            the box around it.\n\n              - *x0*, *y0*, *width*, *height* : location and size of the box\n              - *mutation_size* : a reference scale for the mutation.\n              - *aspect_ratio* : aspect-ratio for the mutation.\n            '''\n            path = ...\n            return path\n\nHere is a complete example.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_custom_boxstyle01_001.png\n   :target: ../../gallery/userdemo/custom_boxstyle01.html\n   :align: center\n   :scale: 50\n\n   Custom Boxstyle01\n\nHowever, it is recommended that you derive from the\nmatplotlib.patches.BoxStyle._Base as demonstrated below.\n\n.. figure:: ../../gallery/userdemo/images/sphx_glr_custom_boxstyle02_001.png\n   :target: ../../gallery/userdemo/custom_boxstyle02.html\n   :align: center\n   :scale: 50\n\n   Custom Boxstyle02\n\n\nSimilarly, you can define a custom ConnectionStyle and a custom ArrowStyle.\nSee the source code of ``lib/matplotlib/patches.py`` and check\nhow each style class is defined.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
